package com.b2c.repository.erp;

import com.alibaba.fastjson.JSON;
import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.apitao.OrderSendQuery;
import com.b2c.entity.ErpOrderEntity;
import com.b2c.entity.ErpOrderItemEntity;
import com.b2c.entity.erp.ErpGoodsSpecEntity;
import com.b2c.entity.erp.ErpSalesOrderEntity;
import com.b2c.entity.erp.vo.FaHuoDaiJianHuoGoodsVo;
import com.b2c.entity.erp.enums.StockOutFormStatusEnum;
import com.b2c.entity.erp.vo.ErpOrderItemListVo;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.result.ResultVo;
import com.b2c.entity.vo.order.DouYinOrderCountVo;
import com.b2c.repository.Tables;
import com.b2c.repository.utils.OrderNumberUtils;
import com.b2c.entity.enums.EnumErpOrderSendStatus;
import com.b2c.entity.enums.erp.EnumErpOrderlogisticsPrintStatus;
import com.b2c.entity.enums.erp.EnumErpSalesOrderStatus;
import com.b2c.entity.vo.OrderItemScanCodeVo;
import com.b2c.entity.vo.OrderScanCodeVo;
import com.b2c.entity.vo.order.OrderWaitSendListVo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.sql.*;
import java.util.*;

/**
 * 描述： 仓库系统订单Repository
 *
 * @author qlp
 * @date 2019-09-17 15:02
 */
@Repository
public class ErpOrderRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;
    @Autowired
    TransactionDefinition transactionDefinition;

    Logger log = LoggerFactory.getLogger(ErpOrderRepository.class);

    /**
     * 查询总页数
     *
     * @return
     */
    protected int getTotalSize() {
        return jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);
    }

    /**
     * 获取待发货的订单列表
     *
     * @param pageIndex
     * @param pageSize
     * @param sendStatus    货物状态
     * @param orderNum
     * @param mobile        收货人手机号
     * @param logisticsCode 快递单号
     * @param startTime
     * @param endTime
     * @return
     */
    @Transactional
    public PagingResponse<OrderWaitSendListVo> getWaitSendOrderList(Integer pageIndex, Integer pageSize,
            EnumErpOrderSendStatus sendStatus, String orderNum, String mobile, String logisticsCode, Integer startTime,
            Integer endTime, Integer saleType, Integer shopId) {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT SQL_CALC_FOUND_ROWS A.*,(SELECT SUM(quantity) FROM " + Tables.ErpOrderItem
                + " WHERE orderId=A.id ) as totalQuantity,shop.name as shopName ");
        sb.append(" FROM " + Tables.ErpOrder + " as A ");
        sb.append(" LEFT JOIN  " + Tables.DcShop + " as shop ON shop.id = A.shopId ");

        // sb.append("SELECT SQL_CALC_FOUND_ROWS A.id, A.order_num,A.payment_result_time
        // as payment_time,A.state,B.mobile,A.type,B.mobile,A.goods_detail ");
        // sb.append(",A.send_company,A.send_code,A.consignee,A.consignee_mobile,A.address,A.type,A.send_status,A.order_detail,A.payment_price
        // ");
        // sb.append(" FROM " + Tables.Order + " A LEFT JOIN " + Tables.User + " B ON
        // A.user_id=B.id ");
        // sb.append(" WHERE A.state = ? ");

        List<Object> params = new ArrayList<>();
        sb.append(" WHERE 1=1 ");
        if (sendStatus != null) {
            if (sendStatus.getIndex() == EnumErpOrderSendStatus.Picked.getIndex()) {
                sb.append(" AND (A.status=? OR A.status=?) ");
                params.add(EnumErpOrderSendStatus.Picked.getIndex());// 状态
                params.add(EnumErpOrderSendStatus.HasOut.getIndex());// 状态

            } else {
                sb.append(" AND A.status=? ");
                params.add(sendStatus.getIndex());// 状态
            }
        }

        if (!StringUtils.isEmpty(orderNum)) {
            sb.append("AND A.order_num = ? ");
            params.add(orderNum);
        }

        if (!StringUtils.isEmpty(mobile)) {
            sb.append("AND A.mobile = ? ");
            params.add(mobile);
        }
        if (!StringUtils.isEmpty(logisticsCode)) {
            sb.append("AND A.logisticsCode = ? ");
            params.add(logisticsCode);
        }
        if (saleType != null) {
            sb.append("AND A.sale_type =? ");
            params.add(saleType);
        }
        if (shopId != null && shopId > 0) {
            sb.append("AND A.shopId =? ");
            params.add(shopId);
        }
        if (startTime != null && startTime > 0) {
            sb.append("AND A.orderTime>=? ");
            params.add(startTime);
        }
        if (endTime != null && endTime > 0) {
            sb.append("AND A.orderTime<=? ");
            params.add(endTime);
        }

        sb.append(" ORDER BY A.id DESC LIMIT ?,?");

        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);

        List<OrderWaitSendListVo> lists = jdbcTemplate.query(sb.toString(),
                new BeanPropertyRowMapper<>(OrderWaitSendListVo.class), params.toArray(new Object[params.size()]));
        int totalSize = getTotalSize();

        if (lists != null && lists.size() > 0) {
            if (sendStatus == EnumErpOrderSendStatus.WaitOut || sendStatus == EnumErpOrderSendStatus.Picking) {
                String itemSQL = "SELECT oi.*,gs.color_value,gs.size_value,gs.color_image FROM " + Tables.ErpOrderItem
                        + " as oi LEFT JOIN " + Tables.ErpGoodsSpec + " as gs on gs.id = oi.skuId WHERE oi.orderId=?";
                for (OrderWaitSendListVo vo : lists) {
                    // try {
                    // jdbcTemplate.queryForObject("SELECT id FROM order_send_express where
                    // order_num=?",Long.class,vo.getOrder_num());
                    // vo.setIsPrint(1);
                    // }catch (Exception e){
                    // vo.setIsPrint(0);
                    // }

                    vo.setItems(jdbcTemplate.query(itemSQL, new BeanPropertyRowMapper<>(ErpOrderItemEntity.class),
                            vo.getId()));
                }
            }
        }
        return new PagingResponse<>(pageIndex, pageSize, totalSize, lists);
    }

    public List<ErpOrderItemListVo> orderWaitSendListExport(Integer startDate, Integer endDate) {
        StringBuffer sb = new StringBuffer();
        sb.append(
                "SELECT i.*,s.color_value,s.size_value,A.order_num from erp_order_item i left join erp_order A on i.orderId=A.id ");
        sb.append(" left join erp_goods_spec s on s.id= i.skuId ");
        List<Object> params = new ArrayList<>();
        sb.append(" WHERE A.status=? ");
        params.add(EnumErpOrderSendStatus.WaitOut.getIndex());// 状态
        if (!StringUtils.isEmpty(startDate)) {
            sb.append("AND A.deliveryTime>=? ");
            params.add(startDate);
        }
        if (!StringUtils.isEmpty(endDate)) {
            sb.append("AND A.deliveryTime<? ");
            params.add(endDate);
        }

        List<ErpOrderItemListVo> lists = jdbcTemplate.query(sb.toString(),
                new BeanPropertyRowMapper<>(ErpOrderItemListVo.class), params.toArray(new Object[params.size()]));
        return lists;
    }

    public PagingResponse<OrderWaitSendListVo> getNewWaitSendOrderList(OrderSendQuery query) {
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT SQL_CALC_FOUND_ROWS A.*,(SELECT SUM(quantity) FROM " + Tables.ErpOrderItem
                + " WHERE orderId=A.id ) as totalQuantity,shop.name as shopName ");
        sb.append(" FROM " + Tables.ErpOrder + " as A ");
        sb.append(" LEFT JOIN  " + Tables.DcShop + " as shop ON shop.id = A.shopId ");

        List<Object> params = new ArrayList<>();

        if (!StringUtils.isEmpty(query.getShopId())) {
            sb.append(" where A.shopId=? ");
            params.add(query.getShopId());
        }
        if (!StringUtils.isEmpty(query.getSendStatus())) {
            if (query.getSendStatus() == EnumErpOrderSendStatus.Picked.getIndex()) {
                sb.append(" AND (A.status=? OR A.status=?) ");
                params.add(EnumErpOrderSendStatus.Picked.getIndex());// 状态
                params.add(EnumErpOrderSendStatus.HasOut.getIndex());// 状态

            } else {
                sb.append(" AND A.status=? ");
                params.add(query.getSendStatus());// 状态
            }
        }

        if (!StringUtils.isEmpty(query.getOrderNum())) {
            sb.append("AND A.order_num = ? ");
            params.add(query.getOrderNum());
        }

        if (!StringUtils.isEmpty(query.getMobile())) {
            sb.append("AND A.mobile = ? ");
            params.add(query.getMobile());
        }
        if (!StringUtils.isEmpty(query.getLogisticsCode())) {
            sb.append("AND A.logisticsCode = ? ");
            params.add(query.getLogisticsCode());
        }

        if (!StringUtils.isEmpty(query.getStartTime())) {
            sb.append("AND A.orderTime>=? ");
            params.add(query.getStartTime());
        }
        if (!StringUtils.isEmpty(query.getStartTime())) {
            sb.append("AND A.orderTime<? ");
            params.add(query.getEndTime());
        }

        sb.append(" ORDER BY A.id DESC LIMIT ?,?");

        params.add((query.getPageIndex() - 1) * query.getPageSize());
        params.add(query.getPageSize());

        List<OrderWaitSendListVo> lists = jdbcTemplate.query(sb.toString(),
                new BeanPropertyRowMapper<>(OrderWaitSendListVo.class), params.toArray(new Object[params.size()]));
        int totalSize = getTotalSize();
        StringBuilder itemSb = new StringBuilder();
        itemSb.append("SELECT oi.*,gs.color_value,gs.size_value,sho.number as locationName FROM  " + Tables.ErpOrderItem
                + " as oi ");
        itemSb.append(" LEFT JOIN " + Tables.ErpGoodsSpec + " as gs on gs.id = oi.skuId ");
        itemSb.append(" left join ").append(Tables.ErpStockLocation).append(" as sho on sho.id = oi.outLocationId");
        itemSb.append(" WHERE oi.orderId=? ");
        lists.forEach(list -> list.setItems(jdbcTemplate.query(itemSb.toString(),
                new BeanPropertyRowMapper<>(ErpOrderItemEntity.class), list.getId())));
        return new PagingResponse<>(query.getPageIndex(), query.getPageSize(), totalSize, lists);
    }

    /**
     * erpOrderItem list
     * 
     * @param startTime
     * @param endTime
     * @return
     */
    public List<ErpOrderItemListVo> getErporderItemSendList(Integer startTime, Integer endTime) {
        List<Object> params = new ArrayList<>();
        StringBuilder sql = new StringBuilder();
        sql.append(
                "SELECT oi.*, e.logisticsCompany,e.logisticsCode,dc.name as shopName,e.sale_type,e.order_num,e.contactPerson,e.mobile,e.address,e.orderTime,e.deliveryTime,e.id as erpOrderId FROM ");
        sql.append(Tables.ErpOrderItem).append(" as oi ");
        sql.append(" LEFT JOIN ").append(Tables.ErpOrder).append(" as e on e.id=oi.orderId ");
        sql.append(" LEFT JOIN ").append(Tables.ErpGoodsSpec).append(" as egs on egs.id=oi.skuId ");
        sql.append(" LEFT JOIN ").append(Tables.ErpGoods).append(" as eg on eg.id=oi.productId ");
        sql.append(" LEFT JOIN ").append(Tables.ErpStockLocation).append(" as sh on sh.id=oi.outLocationId ");
        sql.append(" LEFT JOIN ").append(Tables.DcShop).append(" as dc on dc.id=e.shopId ");
        sql.append(" WHERE e.status=? ");
        params.add(EnumErpOrderSendStatus.HasSend.getIndex());// 状态
        if (startTime != null && startTime > 0) {
            sql.append("AND e.orderTime>=? ");
            params.add(startTime);
        }
        if (endTime != null && endTime > 0) {
            sql.append("AND e.orderTime<? ");
            params.add(endTime);
        }
        return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(ErpOrderItemListVo.class),
                params.toArray(new Object[params.size()]));
    }

    /**
     * 获取订单
     *
     * @param id 订单id
     * @return
     */
    public ErpOrderEntity getOrderEntityById(Long id) {
        String sql = "SELECT o.*,sh.name as shopName FROM " + Tables.ErpOrder + " o LEFT JOIN " + Tables.DcShop
                + " sh on sh.id=o.shopId WHERE o.id=?";
        List<ErpOrderEntity> orders = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ErpOrderEntity.class), id);
        if (orders == null || orders.size() == 0)
            return null;
        else
            return orders.get(0);
    }

    public List<ErpOrderEntity> getOrderEntityByIds(String ids) {
        String sql = "SELECT o.*,sh.name as shopName FROM " + Tables.ErpOrder + " o LEFT JOIN " + Tables.DcShop
                + " sh on sh.id=o.shopId WHERE o.id IN ( " + ids + " )";
        List<ErpOrderEntity> orders = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ErpOrderEntity.class));
        if (orders == null || orders.size() == 0)
            return null;
        else
            return orders;
    }

    /**
     * 获取订单
     *
     * @param num 订单编号
     * @return
     */
    public ErpOrderEntity getOrderEntityByNum(String num) {
        List<ErpOrderEntity> orders = jdbcTemplate.query("SELECT * FROM " + Tables.ErpOrder + " WHERE order_num=?",
                new BeanPropertyRowMapper<>(ErpOrderEntity.class), num);
        if (orders == null || orders.size() == 0)
            return null;
        else
            return orders.get(0);
    }

    /**
     * 根据订单id获取erp系统中的商品信息
     *
     * @param orderId
     * @return
     */
    public List<ErpOrderItemListVo> getErpOrderItemsByOrderId(Long orderId) {
        StringBuilder sql = new StringBuilder();
        sql.append(
                "SELECT oi.*,egs.specNumber,egs.color_value,egs.size_value,egs.style_value,eg.name as goodsName,eg.number as productNumber,sh.name as locationName,oi.quantity  FROM ");
        sql.append(Tables.ErpOrderItem).append(" as oi ");
        sql.append(" LEFT JOIN ").append(Tables.ErpGoodsSpec).append(" as egs on egs.id=oi.skuId ");
        sql.append(" LEFT JOIN ").append(Tables.ErpGoods).append(" as eg on eg.id=oi.productId ");
        sql.append(" LEFT JOIN ").append(Tables.ErpStockLocation).append(" as sh on sh.id=oi.outLocationId ");
        // sql.append(" LEFT JOIN ").append(Tables.ErpReservoir).append(" as sr on
        // sr.id=oi.outReservoirId ");
        // sql.append(" LEFT JOIN ").append(Tables.ErpStockLocation).append(" as ss on
        // ss.id=oi.outShelfId ");
        sql.append(" WHERE orderId=? ");

        return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(ErpOrderItemListVo.class), orderId);
    }

    /**
     * 按订单items批量生成拣货单
     * 
     * @param orderItemIdList
     * @return
     */
    @Transactional
    public ResultVo<Long> generatingPickingListByOrderItem(List<Long> orderItemIdList) {
        /************ 查询要加入拣货的订单items ***************/
        Map<String, Object> args = new HashMap<>();
        args.put("ids", orderItemIdList);
        NamedParameterJdbcTemplate givenParamJdbcTemp = new NamedParameterJdbcTemplate(jdbcTemplate);

        StringBuilder sb = new StringBuilder();
        sb.append("SELECT SUM(oi.quantity) AS quantity,oi.skuNumber ");
        // sb.append(",productMallName,productId,productNumber,skuId,skuNumber,productImgUrl");
        sb.append(",(SELECT SUM(currentQty) FROM erp_goods_stock_info WHERE specId=skuId AND isDelete=0) AS currentQty " );
        //sb.append(",(SELECT SUM(lockedQty) FROM erp_goods_stock_info WHERE specId=skuId AND isDelete=0) AS lockedQty" );
        sb.append(" FROM erp_order_item oi WHERE oi.id IN (:ids) GROUP BY oi.skuId");

        List<ErpOrderItemEntity> itemList = givenParamJdbcTemp.query(sb.toString(), args,
                new BeanPropertyRowMapper<>(ErpOrderItemEntity.class));
        /************ 判断订单商品库存 ************/
        for (var item : itemList) {
            // 查询库存
            long keyongQty = item.getCurrentQty();
            if (keyongQty < item.getQuantity().longValue()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new ResultVo<>(EnumResultVo.DataError, item.getSkuNumber() + "可用库存不足，不能操作");
            }
        }

        // 生成拣货单号
        String no = "OUT" + OrderNumberUtils.getOrderIdByTime();
        int goodsTotal = 0;// 已处理的商品数量

        /************ 1、生成拣货单信息 *************/
        /********** 添加拣货单表erp_stock_out_form单据数据 ***********/
        String formSQL = "INSERT INTO " + Tables.ErpStockOutForm
                + " (stockOutNo,status,printStatus,createTime,createBy,outType,remark) VALUE (?,?,?,?,?,?,?)";

        String remark = "订单item批量拣货，订单Item总数：" + orderItemIdList.size();// +JSON.toJSONString(orderItemIdList);
        log.info(remark);
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(formSQL, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, no);
                ps.setInt(2, StockOutFormStatusEnum.Packing.getIndex());
                ps.setInt(3, 0);
                ps.setLong(4, System.currentTimeMillis() / 1000);
                ps.setString(5, "SYSTEM");
                ps.setInt(6, 1);// 出库类型1订单拣货出库2采购退货出库
                ps.setString(7, remark);
                return ps;
            }
        }, keyHolder);

        Long stockOutId = keyHolder.getKey().longValue();// 拣货单id

        for (Long orderItemId : orderItemIdList) {
            Long stockOutFormItemId = 0l;// 拣货单明细id

            /************ 查询order_item **************/
            var orderItem = jdbcTemplate.queryForObject("SELECT * FROM " + Tables.ErpOrderItem + " WHERE id=?",
                    new BeanPropertyRowMapper<>(ErpOrderItemEntity.class), orderItemId);

            try {
                // 拣货单明细存在，
                var formitemExist = jdbcTemplate.queryForObject(
                        "SELECT id FROM " + Tables.ErpStockOutFormItem + " WHERE formId=? AND itemId =?", long.class,
                        stockOutId, orderItemId);

                stockOutFormItemId = formitemExist;

            } catch (Exception e) {
                // 拣货单明细不存在，添加
                /************* 一、添加拣货单明细 stock_out_form_item ***************/
                String formItemSQL = "INSERT INTO " + Tables.ErpStockOutFormItem
                        + " (formId,itemId,goodsId,specId,locationId,quantity,completeTime,status) VALUE (?,?,?,?,?,?,?,?)";
                // jdbcTemplate.update(formItemSQL, stockOutId, orderItemId,
                // orderItem.getProductId(),
                // orderItem.getSkuId(), 0, orderItem.getQuantity(), 0,
                // StockOutFormStatusEnum.Packing.getIndex());

                KeyHolder keyHolderFormItem = new GeneratedKeyHolder();
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                        PreparedStatement ps = connection.prepareStatement(formItemSQL,
                                Statement.RETURN_GENERATED_KEYS);
                        ps.setLong(1, stockOutId);
                        ps.setLong(2, orderItemId);
                        ps.setInt(3, orderItem.getProductId());
                        ps.setInt(4, orderItem.getSkuId().intValue());
                        ps.setInt(5, 0);
                        ps.setInt(6, orderItem.getQuantity().intValue());
                        ps.setInt(7, 0);
                        ps.setInt(8, StockOutFormStatusEnum.Packing.getIndex());
                        return ps;
                    }
                }, keyHolderFormItem);

                stockOutFormItemId = keyHolderFormItem.getKey().longValue();//
            }

            /************* 二、更新订单order_item状态为拣货中 ***************/

            String orderItemUpdateSQL = "UPDATE " + Tables.ErpOrderItem
                    + " SET status=?,stockOutFormId=?,stockOutFormItemId=? WHERE id=?";
            jdbcTemplate.update(orderItemUpdateSQL, EnumErpOrderSendStatus.Picking.getIndex(), stockOutId,
                    stockOutFormItemId, orderItemId);

            /************* 三、更新订单order状态为拣货中 ***************/
            /********* 查询同订单items信息 **********/
            var orderItems = jdbcTemplate.query(
                    "SELECT id,orderId,`status` FROM " + Tables.ErpOrderItem + " WHERE orderId=?",
                    new BeanPropertyRowMapper<>(ErpOrderItemEntity.class), orderItem.getOrderId());
            boolean isAllOut = true;// 是否全部出库
            for (var item : orderItems) {
                if (item.getStatus().intValue() != 1) {
                    isAllOut = false;
                    break;
                }
            }
            if (isAllOut) {
                /********** 如果全部出库则更新订单状态为拣货中 *************/
                /********** 1、更新订单状态为拣货中 ErpOrderStatusEnums.Picking ***********/
                jdbcTemplate.update("UPDATE " + Tables.ErpOrder + " SET status=?,pickingTime=?,modifyTime=? WHERE id=?",
                        EnumErpOrderSendStatus.Picking.getIndex(), System.currentTimeMillis() / 1000,
                        System.currentTimeMillis() / 1000, orderItem.getOrderId());
            }
            goodsTotal++;
        }
        log.info("生成拣货单成，拣货单ID：" + stockOutId);
        // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return new ResultVo<>(EnumResultVo.SUCCESS, stockOutId);
    }

    /**
     * 按订单批量生成拣货单
     *
     * @param orderIdList
     * @return
     */
    @Transactional
    public ResultVo<Long> generatingPickingListByOrder(List<Long> orderIdList) {
        /************ 查询要加入拣货的订单 ***************/
        String sql = "SELECT * FROM " + Tables.ErpOrder + " WHERE id in (:ids)";
        Map<String, Object> args = new HashMap<>();
        args.put("ids", orderIdList);
        NamedParameterJdbcTemplate givenParamJdbcTemp = new NamedParameterJdbcTemplate(jdbcTemplate);
        // 加入拣货单的订单list
        // List<ErpOrderEntity> orderList = givenParamJdbcTemp.query(sql, args, new
        // BeanPropertyRowMapper<>(ErpOrderEntity.class));

        // 加入拣货单的订单商品list（去重）
        // String itemSQL = "SELECT
        // productMallName,productId,productNumber,skuId,skuNumber,productImgUrl,SUM(quantity)
        // AS quantity FROM erp_order_item WHERE orderId IN (:ids) GROUP BY skuId";
        StringBuilder sb = new StringBuilder();
        sb.append(
                "SELECT productMallName,productId,productNumber,skuId,skuNumber,productImgUrl,SUM(oi.quantity) AS quantity");
        sb.append(",(SELECT SUM(currentQty) FROM erp_goods_stock_info WHERE specId=skuId AND isDelete=0) AS currentQty ");
        //sb.append(",(SELECT SUM(lockedQty) FROM erp_goods_stock_info WHERE specId=skuId AND isDelete=0) AS lockedQty");
        sb.append(",IFNULL((SELECT SUM(it1.quantity) FROM erp_order_item AS it1 WHERE it1.skuId=oi.skuId AND  it1.`status` = 1 AND it1.orderId NOT IN (:ids)),0) AS pickingQty");// 拣货中的订单items计算总数

        // sb.append(",(SELECT SUM(it1.quantity) FROM erp_order_item AS it1 WHERE
        // it1.skuId=skuId AND (it1.`status` = 0 OR it1.`status` = 1)) AS pickingQty");
        sb.append(" FROM erp_order_item oi WHERE oi.orderId IN (:ids) GROUP BY oi.skuId");

        List<ErpOrderItemEntity> itemList = givenParamJdbcTemp.query(sb.toString(), args,
                new BeanPropertyRowMapper<>(ErpOrderItemEntity.class));
        /************ 判断订单商品库存 ************/
        for (var item : itemList) {
            // 查询库存
            long keyongQty = item.getCurrentQty() - item.getPickingQty();
            if (keyongQty < item.getQuantity().longValue()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new ResultVo<>(EnumResultVo.DataError, item.getSkuNumber() + "可用库存不足，不能操作");
            }
        }

        int orderTotal = 0;// 已处理的订单数量
        int goodsTotal = 0;// 已处理的商品数量
        /************ 1、生成拣货单信息 *************/
        // 生成拣货单号
        String no = "OUT" + OrderNumberUtils.getOrderIdByTime();

        /********** 添加拣货单表erp_stock_out_form单据数据 ***********/
        String formSQL = "INSERT INTO " + Tables.ErpStockOutForm
                + " (stockOutNo,status,printStatus,createTime,createBy,outType,remark) VALUE (?,?,?,?,?,?,?)";
        String remark = "订单批量拣货，订单ID：" + JSON.toJSONString(orderIdList);
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement ps = connection.prepareStatement(formSQL, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, no);
                ps.setInt(2, StockOutFormStatusEnum.Packing.getIndex());
                ps.setInt(3, 0);
                ps.setLong(4, System.currentTimeMillis() / 1000);
                ps.setString(5, "SYSTEM");
                ps.setInt(6, 1);// 出库类型1订单拣货出库2采购退货出库
                ps.setString(7, remark);
                return ps;
            }
        }, keyHolder);

        Long stockOutId = keyHolder.getKey().longValue();

        for (Long orderId : orderIdList) {

            /********** 查询订单信息 ***********/
            String orderSQL = "SELECT * FROM " + Tables.ErpOrder + " WHERE id=?";
            var order = jdbcTemplate.queryForObject(orderSQL, new BeanPropertyRowMapper<>(ErpOrderEntity.class),
                    orderId);

            if (order.getStatus().intValue() == EnumErpOrderSendStatus.WaitOut.getIndex()) {

                /********** 1、更新订单状态为拣货中 ErpOrderStatusEnums.Picking ***********/
                jdbcTemplate.update("UPDATE " + Tables.ErpOrder + " SET status=?,pickingTime=?,modifyTime=? WHERE id=?",
                        EnumErpOrderSendStatus.Picking.getIndex(), System.currentTimeMillis() / 1000,
                        System.currentTimeMillis() / 1000, orderId);

                var items = jdbcTemplate.query("SELECT * FROM " + Tables.ErpOrderItem + " WHERE orderId=?",
                        new BeanPropertyRowMapper<>(ErpOrderItemEntity.class), orderId);
                if (items != null && items.size() > 0) {

                    for (var item : items) {

                        Long stockOutFormItemId = 0l;// 拣货单明细id

                        try {
                            // 拣货单明细存在，
                            var formitemExist = jdbcTemplate.queryForObject(
                                    "SELECT id FROM " + Tables.ErpStockOutFormItem + " WHERE formId=? AND itemId =?",
                                    long.class, stockOutId, item.getId());

                            stockOutFormItemId = formitemExist;

                        } catch (Exception e) {
                            // 拣货单明细不存在，添加
                            /************* 一、添加拣货单明细 stock_out_form_item ***************/
                            String formItemSQL = "INSERT INTO " + Tables.ErpStockOutFormItem
                                    + " (formId,itemId,goodsId,specId,locationId,quantity,completeTime,status) VALUE (?,?,?,?,?,?,?,?)";
                            // jdbcTemplate.update(formItemSQL, stockOutId, orderItemId,
                            // orderItem.getProductId(),
                            // orderItem.getSkuId(), 0, orderItem.getQuantity(), 0,
                            // StockOutFormStatusEnum.Packing.getIndex());

                            KeyHolder keyHolderFormItem = new GeneratedKeyHolder();
                            jdbcTemplate.update(new PreparedStatementCreator() {
                                @Override
                                public PreparedStatement createPreparedStatement(Connection connection)
                                        throws SQLException {
                                    PreparedStatement ps = connection.prepareStatement(formItemSQL,
                                            Statement.RETURN_GENERATED_KEYS);
                                    ps.setLong(1, stockOutId);
                                    ps.setLong(2, item.getId());
                                    ps.setInt(3, item.getProductId());
                                    ps.setInt(4, item.getSkuId().intValue());
                                    ps.setInt(5, 0);
                                    ps.setInt(6, item.getQuantity().intValue());
                                    ps.setInt(7, 0);
                                    ps.setInt(8, StockOutFormStatusEnum.Packing.getIndex());
                                    return ps;
                                }
                            }, keyHolderFormItem);

                            stockOutFormItemId = keyHolderFormItem.getKey().longValue();//
                        }

                        /********** 2、更新订单item为拣货中，并且更新stockOutFormId **********/
                        String orderItemUpdateSQL = "UPDATE " + Tables.ErpOrderItem
                                + " SET status=?,stockOutFormId=?,stockOutFormItemId=? WHERE orderId=?";
                        jdbcTemplate.update(orderItemUpdateSQL, EnumErpOrderSendStatus.Picking.getIndex(), stockOutId,
                                stockOutFormItemId, orderId);

                        // /************* 一、添加拣货单明细 stock_out_form_item ***************/
                        // String formItemSQL = "INSERT INTO " + Tables.ErpStockOutFormItem
                        //         + " (formId,itemId,goodsId,specId,locationId,quantity,completeTime,status) VALUE (?,?,?,?,?,?,?,?)";
                        // jdbcTemplate.update(formItemSQL, stockOutId, item.getId(), item.getProductId(), item.getSkuId(),
                        //         0, item.getQuantity(), 0, StockOutFormStatusEnum.Packing.getIndex());

                        goodsTotal++;
                    }

                }

                orderTotal++;
            }

        }
        // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return new ResultVo<>(EnumResultVo.SUCCESS, stockOutId);
    }

    /**
     * 订单发货
     *
     * @param orderId 订单Id
     * @return
     */
    @Transactional
    public ResultVo<Integer> sendOrder(Long orderId) {
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        /****** 1、查询表单 *******/
        ErpOrderEntity order = getOrderEntityById(orderId);
        if (null == order)
            return new ResultVo<>(EnumResultVo.Fail, "订单不存在");

        else if (order.getStatus().intValue() == EnumErpOrderSendStatus.HasSend.getIndex())
            return new ResultVo<>(EnumResultVo.DataError, "该订单已经发货了");
        else if (order.getStatus().intValue() != EnumErpOrderSendStatus.HasOut.getIndex())
            return new ResultVo<>(EnumResultVo.DataError, "订单还没走完流程，不能发货");

        if (StringUtils.isEmpty(order.getLogisticsCode()))
            new ResultVo<>(EnumResultVo.DataError, "没有物流单号，不能发货");

        /******** 2、查询订单item ***********/
        StringBuilder itemSQL = new StringBuilder("SELECT sout.*,so.stockOutNo,sh.number as locationName ");
        itemSQL.append(",concat('颜色:',gs.color_value,'尺码:',gs.size_value) skuName");
        itemSQL.append(" FROM " + Tables.ErpOrderItem + " sout ");
        itemSQL.append("LEFT JOIN erp_stock_out_form AS so on so.id = sout.stockOutFormId ");
        itemSQL.append("LEFT JOIN erp_stock_location AS sh on sh.id = sout.outLocationId ");
        itemSQL.append("LEFT JOIN ").append(Tables.ErpGoodsSpec).append(" as gs on gs.id = sout.skuId ");
        itemSQL.append(" WHERE sout.orderId=?");

        List<ErpOrderItemEntity> orderItems = jdbcTemplate.query(itemSQL.toString(),
                new BeanPropertyRowMapper<>(ErpOrderItemEntity.class), order.getId());
        if (orderItems == null || orderItems.size() == 0)
            new ResultVo<>(EnumResultVo.DataError, "订单数据错误[没有items]，不能发货");

        /******** 判断订单明细商品是否都已经出库 **********/
        for (var item : orderItems) {
            if (item.getStatus().intValue() != StockOutFormStatusEnum.OUTED.getIndex()) {
                // 订单还有没有出库的商品
                new ResultVo<>(EnumResultVo.DataError, "订单还有没有出库的商品，不能发货");
            }
        }

        /******** 1、更新仓库 ErpOrder 订单状态--已发货 ***********/
        jdbcTemplate.update("UPDATE " + Tables.ErpOrder + " SET status=?,deliveryTime=?,modifyTime=? where id=?",
                EnumErpOrderSendStatus.HasSend.getIndex(), System.currentTimeMillis() / 1000,
                System.currentTimeMillis() / 1000, order.getId());

        Long payTime = 0l;// 订单支付时间
        Double payAmount = 0.0;// 订单支付金额
        Integer payStatus = -1;// 订单支付状态 付款状态（0未付款1部分付款2完全付款）
        Integer payMethod = -1;// 订单支付方式 （1微信支付，2支付宝支付,3线下支付）
        Integer developerId = 0;// 业务员id
        /*************** 根据店铺id shopId 更新OMS系统发货状态 *****************/
//        jdbcTemplate.update("UPDATE " + Tables.ErpSalesOrder
//                + " SET logisticsCompany=?,logisticsCompanyCode=?,logisticsCode=?,deliveredStatus=?,deliveredTime=?,status=? WHERE orderNum=? AND shopId=?",
//                order.getLogisticsCompany(), order.getLogisticsCompanyCode(), order.getLogisticsCode(),
//                EnumErpOrderSendStatus.HasSend.getIndex(), System.currentTimeMillis() / 1000,
//                EnumErpSalesOrderStatus.Delivered.getIndex(), order.getOrder_num(), order.getShopId());

        if (order.getShopId() == 99 || order.getShopId() == 9) {

                // 外发订单，erp_sales_order
                var orderTmp = jdbcTemplate.queryForObject("SELECT * FROM " + Tables.ErpSalesOrder + " WHERE orderNum=?",
                        new BeanPropertyRowMapper<>(ErpSalesOrderEntity.class), order.getOrder_num());

                //更新ERP订单状态
                jdbcTemplate.update("UPDATE " + Tables.ErpSalesOrder
                                + " SET logisticsCompany=?,logisticsCompanyCode=?,logisticsCode=?,deliveredStatus=?,deliveredTime=?,status=? WHERE orderNum=?",
                        order.getLogisticsCompany(), order.getLogisticsCompanyCode(), order.getLogisticsCode(),
                        EnumErpOrderSendStatus.HasSend.getIndex(), System.currentTimeMillis() / 1000,
                        EnumErpSalesOrderStatus.Delivered.getIndex(), order.getOrder_num());

                //更新ERP订单item状态
                jdbcTemplate.update("UPDATE " + Tables.ErpSalesOrderItem + " SET itemStatus=1 WHERE orderId=?", orderTmp.getId());

        }  else if (order.getShopId() == 8 || order.getShopId() == 19 || order.getShopId() == 20) {
            // 抖音
            jdbcTemplate.update(
                    "UPDATE dc_douyin_orders SET logistics_company=?,logistics_code=?,send_status=?,send_time=? WHERE order_id=? ",
                    order.getLogisticsCompany(), order.getLogisticsCode(), 4, System.currentTimeMillis() / 1000,
                    order.getOrder_num());
        } /*
           * else if (order.getShopId() == 9) { //批批网 jdbcTemplate.
           * update("UPDATE dc_pipi_order SET logisticsCompany=?,logisticsCompanyCode=?,logisticsCode=?,sendStatus=?,sendTime=? WHERE orderNum=?"
           * , order.getLogisticsCompany(), order.getLogisticsCompanyCode(),
           * order.getLogisticsCode(), 4, System.currentTimeMillis() / 1000,
           * order.getOrder_num()); }
           */
//        else if (order.getShopId() == 13) {
//            jdbcTemplate.update(
//                    "UPDATE dc_kwai_order SET logisticsCompany=?,logisticsCompanyCode=?,logisticsCode=?,sendStatus=?,sendTime=? WHERE oid=?",
//                    order.getLogisticsCompany(), order.getLogisticsCompanyCode(), order.getLogisticsCode(), 4,
//                    System.currentTimeMillis() / 1000, order.getOrder_num());
//        }

        /****
         *************** 新增一条财务结算数据 fms_sales_statements***************** String statementsSQL =
         * "INSERT INTO "+Tables.FmsSalesStatements+" " +
         * "(shopId,clientName,clientMobile,clientAddress," +
         * "developerId,orderNum,totalAmount,shippingFee,orderTime," +
         * "payTime,payAmount,payStatus,payMethod," +
         * "deliveredTime,logisticsCode,logisticsCompany," +
         * "saleType,status,createTime,sellerMemo) " + "VALUE
         * (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
         * 
         * KeyHolder keyHolder = new GeneratedKeyHolder(); Integer finalDeveloperId =
         * developerId; Long finalPayTime = payTime; Double finalPayAmount = payAmount;
         * Integer finalPayStatus = payStatus; Integer finalPayMethod = payMethod;
         * jdbcTemplate.update(new PreparedStatementCreator() {
         * 
         * @Override public PreparedStatement createPreparedStatement(Connection
         *           connection) throws SQLException { PreparedStatement ps =
         *           connection.prepareStatement(statementsSQL,
         *           Statement.RETURN_GENERATED_KEYS); ps.setInt(1, order.getShopId());
         *           ps.setString(2, order.getContactPerson()); ps.setString(3,
         *           order.getMobile()); ps.setString(4, order.getAddress());
         *           ps.setInt(5, finalDeveloperId); ps.setString(6,
         *           order.getOrder_num()); ps.setBigDecimal(7,order.getTotalAmount());
         *           ps.setBigDecimal(8,order.getShippingFee());
         *           ps.setLong(9,order.getOrderTime()); ps.setLong(10, finalPayTime);
         *           ps.setBigDecimal(11,new BigDecimal(finalPayAmount)); ps.setInt(12,
         *           finalPayStatus); ps.setInt(13, finalPayMethod);
         *           ps.setLong(14,System.currentTimeMillis() / 1000 );
         *           ps.setString(15,order.getLogisticsCode());
         *           ps.setString(16,order.getLogisticsCompany());
         *           ps.setInt(17,order.getSaleType()); ps.setInt(18,0);
         *           ps.setLong(19,System.currentTimeMillis() / 1000);
         *           ps.setString(20,order.getSellerMemo()); return ps; } }, keyHolder);
         * 
         *           Long statementsId = keyHolder.getKey().longValue();
         *************** 
         * 
         *           新增财务结算明细数据 fms_sales_statements_sku***************** String
         *           statementsSkuSQL = "INSERT INTO "+Tables.FmsSalesStatementsSku+" "
         *           +
         *           "(statementsId,itemAmount,goodsName,goodsNumber,skuNumber,skuName,quantity,stockOutFormNumber,stockOutLocationNumber)
         *           VALUE (?,?,?,?,?,?,?,?,?)";
         * 
         *           for (var it:orderItems) {
         *           jdbcTemplate.update(statementsSkuSQL,statementsId,it.getItemAmount(),it.getProductMallName(),it.getProductNumber(),it.getSkuNumber(),it.getSkuName(),it.getQuantity(),it.getStockOutNo(),it.getLocationName());
         *           }
         ***/

        return new ResultVo<>(EnumResultVo.SUCCESS);
        // try {
        // /******** 1、更新仓库 ErpOrder 订单状态--已发货***********/
        // jdbcTemplate.update("UPDATE " + Tables.ErpOrder + " SET
        // status=?,deliveryTime=?,modifyTime=? where id=?"
        // , ErpOrderStatusEnums.HasSend.getIndex(), System.currentTimeMillis() / 1000,
        // System.currentTimeMillis() / 1000, order.getId());
        //
        // /*************** 2、跟进order_item更新库存信息 **************/
        // if (orderItems != null && orderItems.size() > 0) {
        // for (var item : orderItems) {
        //
        // /********2.1、更新商品库存_erp_goods_spec***********/
        // jdbcTemplate.update("UPDATE " + Tables.ErpGoodsSpec + " SET
        // currentQty=currentQty-? WHERE id=?", item.getQuantity(), item.getSkuId());
        //
        // /********2.2、更新商品库存_erp_goods_stock_info***********/
        // String updErpGoodsStock = "UPDATE " + Tables.ErpGoodsStockInfo + " SET
        // currentQty=currentQty-? WHERE goodsId=? AND specId=? AND locationId=? ";
        // jdbcTemplate.update(updErpGoodsStock, item.getQuantity(),
        // item.getProductId(), item.getSkuId(), item.getOutLocationId());
        //
        // /********2.3、更新erp_order_item***********/
        // //更新订单明细出库状态、出库仓位 status，outLocationId
        // jdbcTemplate.update("UPDATE " + Tables.ErpOrderItem + " SET status=? WHERE
        // id=?",
        // StockOutFormStatusEnum.OUTED.getIndex(), item.getId());
        //
        // /************* 2.4、加入库存日志erp_goods_stock_logs*****************/
        // String remark = "订单发货出库，订单号：" + order.getOrder_num();
        // remark += " 订单来源：" + order.getSource();
        // remark += " SKU：" + item.getSkuNumber();
        // String logsSQL = "INSERT INTO " + Tables.ErpGoodsStockLogs + "
        // (goodsId,goodsNumber,specId,specNumber,locationId,quantity,createTime,type,sourceType,sourceId,remark)
        // VALUE (?,?,?,?,?,?,?,?,?,?,?)";
        // jdbcTemplate.update(logsSQL,
        // item.getProductId(), item.getProductNumber(), item.getSkuId(),
        // item.getSkuNumber(), item.getOutLocationId(), item.getQuantity(),
        // new Date(), EnumGoodsStockLogType.OUT.getIndex(),
        // EnumGoodsStockLogSourceType.OrderSend.getIndex(),orderId, remark);
        // }
        // }
        //
        //
        // /******************************更新来源订单状态等信息*********************************/
        //// if (order.getSource().equals(ErpOrderSourceEnum.OFFLINE.getIndex()) ||
        // order.getSource().equals(ErpOrderSourceEnum.YUNGOU.getIndex())) {
        //// //下单系统和华衣云购平台订单
        ////
        ////
        //// /********1.1、更新用户订单状态--已发货***********/
        //// jdbcTemplate.update("update " + Tables.Order + " set
        // state=?,send_company=?,send_company_code=?,send_code=?,send_time=unix_timestamp(now()),send_status=?
        // where order_num=?",
        //// OrderStateEnums.Delivered.getIndex(), order.getLogisticsCompany(),
        // order.getLogisticsCompanyCode(), order.getLogisticsCode(),
        // ErpOrderStatusEnums.HasSend.getIndex(), order.getOrder_num());
        ////
        //// /**1.2、添加订单日志 order_logs**/
        //// String logsSQL = "INSERT INTO " + Tables.OrderLogs + "
        // (order_id,type,comment,create_on,create_by) VALUE (?,?,?,?,?)";
        //// jdbcTemplate.update(logsSQL, order.getId(), 0, "订单发货",
        // System.currentTimeMillis() / 1000, "system");
        //// /**1.3、新增订单物流信息order_logistics**/
        //// String orderLogistics = "INSERT " + Tables.OrderLogistics + "
        // (comment,order_id,create_on,create_by,state,type) VALUES (?,?,?,?,?,?)";
        //// jdbcTemplate.update(orderLogistics, "订单已发货", order.getId(),
        // System.currentTimeMillis() / 1000, "", 0, 0);
        ////
        //// }else if(order.getSource().equals(ErpOrderSourceEnum.ALIBABA.getIndex())){
        //// //阿里巴巴订单
        //// try {
        //// jdbcTemplate.update("UPDATE " + Tables.DcAliOrder + " SET status=? WHERE
        // id=?", EnumAliOrderStatus.waitbuyerreceive.getIndex(), order.getOrder_num());
        //// }catch (Exception e){}
        //// }else if(order.getSource().equals(ErpOrderSourceEnum.YOUZAN.getIndex())){
        //// //有赞订单
        //// try {
        //// jdbcTemplate.update("UPDATE " + Tables.dcYzOrder + " SET status=? WHERE
        // orderNum=?", OrderStateEnums.Delivered.getIndex(), order.getOrder_num());
        //// }catch (Exception e){}
        //// }
        //
        // return new ResultVo<>(EnumResultVo.SUCCESS);
        //
        // } catch (Exception e) {
        // log.error("订单ID:" + orderId + "发货异常信息：" + e);
        // dataSourceTransactionManager.rollback(transactionStatus);
        // return new ResultVo<>(EnumResultVo.Fail, "订单发货异常");
        // }

    }

    /**
     * 手动快递单发货
     *
     * @param erpOrderId
     * @param company
     * @param companyCode
     * @param code
     * @return
     */
    public ResultVo<Integer> orderHandExpress(Integer erpOrderId, String company, String companyCode, String code) {
        try {
            var eOrder = jdbcTemplate.queryForObject("select * from " + Tables.ErpOrder + " where id=?",
                    new BeanPropertyRowMapper<>(ErpOrderEntity.class), erpOrderId);

            // if(eOrder.getStatus() == ErpOrderStatusEnums.HasOut.getIndex())return new
            // ResultVo<>(EnumResultVo.Fail, "快递单打印");

            /******** 更新快递信息 *********/
            String updErpOrderSQL = "UPDATE " + Tables.ErpOrder
                    + " SET logisticsCompany=?,logisticsCompanyCode=?,logisticsCode=?,modifyTime=?,logisticsPrintStatus=?,logisticsPrintCount=logisticsPrintCount+1,logisticsPrintTime=?,logisticsPrintType=1 WHERE id=? ";
            jdbcTemplate.update(updErpOrderSQL, company, companyCode, code, System.currentTimeMillis() / 1000,
                    EnumErpOrderlogisticsPrintStatus.Printed.getIndex(), System.currentTimeMillis() / 1000, erpOrderId);

            /******** 插入order_send_express *********/
            String addSendExpress = "INSERT INTO order_send_express set order_num=?,send_company_code=?,send_code=?,send_print_img=?,create_on=unix_timestamp(now())";
            jdbcTemplate.update(addSendExpress, eOrder.getOrder_num(), companyCode, code, "");

            return new ResultVo<>(EnumResultVo.SUCCESS, "操作成功");
        } catch (Exception e) {
            return new ResultVo<>(EnumResultVo.Fail, "手动填写快递单信息异常");
        }
    }

    /**
     * 取消订单确认
     *
     * @param erpOrderIdArray
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultVo<Integer> cancelOrderConfirm(List<Long> erpOrderIdArray) {
        int errorOrderTotal = 0;// 已处理的订单数量
        int successOrderTotal = 0;
        for (Long erpOrderId : erpOrderIdArray) {
            // 查询订单
            var erpOrders = jdbcTemplate.query("SELECT * FROM " + Tables.ErpOrder + " WHERE id=?",
                    new BeanPropertyRowMapper<>(ErpOrderEntity.class), erpOrderId);

            if (erpOrders == null || erpOrders.size() == 0)
                return new ResultVo<>(EnumResultVo.ParamsError, "订单单不存在");
            var erpOrder = erpOrders.get(0);

            // 订单状态检查
            if (erpOrder.getStatus().intValue() == EnumErpOrderSendStatus.Picking.getIndex()) {
                return new ResultVo<>(EnumResultVo.ParamsError, "订单正在拣货中,无法取消");
            } else if (erpOrder.getStatus().intValue() == EnumErpOrderSendStatus.Picked.getIndex()) {
                return new ResultVo<>(EnumResultVo.ParamsError, "订单已完成拣货,无法取消");
            } else if (erpOrder.getStatus().intValue() == EnumErpOrderSendStatus.HasOut.getIndex()) {
                return new ResultVo<>(EnumResultVo.ParamsError, "订单已出库,无法取消");
            } else if (erpOrder.getStatus().intValue() == EnumErpOrderSendStatus.HasSend.getIndex()) {
                return new ResultVo<>(EnumResultVo.ParamsError, "订单已发货,无法取消");
            }
            if (erpOrder.getStatus().intValue() != EnumErpOrderSendStatus.WaitOut.getIndex())
                return new ResultVo<>(EnumResultVo.ParamsError, "订单不是待出库状态，不能取消");

            try {
                // 删除订单明细
                jdbcTemplate.update("delete from " + Tables.ErpOrderItem + " where orderId=?", erpOrder.getId());
                // 删除订单
                jdbcTemplate.update("delete from " + Tables.ErpOrder + " where id=?", erpOrder.getId());

                if (erpOrder.getShopId() == 99) {
                    // 外发订单取消
                    jdbcTemplate.update(
                            "UPDATE " + Tables.ErpSalesOrder
                                    + " SET auditStatus=0,status=1,deliveredStatus=0 WHERE orderNum=?",
                            erpOrder.getOrder_num());
                } else if (erpOrder.getShopId() == 1) {
                    // 阿里店铺
                    jdbcTemplate.update("UPDATE " + Tables.DcAliOrder + " SET auditStatus=0,send_status=0 WHERE id=?",
                            erpOrder.getOrder_num());
                } else if (erpOrder.getShopId() == 2 || erpOrder.getShopId() == 6 || erpOrder.getShopId() == 7) {
                    // 天猫淘宝
                    jdbcTemplate.update("UPDATE " + Tables.DcTmallOrder + " SET auditStatus=0,send_status=0 WHERE id=?",
                            erpOrder.getOrder_num());
                } else if (erpOrder.getShopId() == 3 || erpOrder.getShopId() == 4 || erpOrder.getShopId() == 11) {
                    // 云购平台
                    jdbcTemplate.update("UPDATE " + Tables.Order + " SET auditStatus=0,send_status=0 WHERE order_num=?",
                            erpOrder.getOrder_num());
                } else if (erpOrder.getShopId() == 5 || erpOrder.getShopId() == 18) {
                    // 拼多多
                    jdbcTemplate.update("UPDATE dc_pdd_orders SET auditStatus=0,send_status=0 WHERE order_sn=?",
                            erpOrder.getOrder_num());
                } else if (erpOrder.getShopId() == 8) {
                    // 抖音
                    jdbcTemplate.update("UPDATE dc_douyin_orders SET auditStatus=0,send_status=0 WHERE order_id=?",
                            erpOrder.getOrder_num());
                } else if (erpOrder.getShopId() == 9) {
                    // 批批网
                    jdbcTemplate.update("UPDATE dc_pipi_order SET auditStatus=0,sendStatus=0 WHERE orderNum=?",
                            erpOrder.getOrder_num());
                }

                /**************** 删除erp_sales_order数据 ******************/
                if (erpOrder.getShopId() != 99) {
                    try {
                        var salesOrder = jdbcTemplate.queryForObject(
                                "SELECT * FROM erp_sales_order  WHERE orderNum=? AND shopId=?",
                                new BeanPropertyRowMapper<>(ErpSalesOrderEntity.class), erpOrder.getOrder_num(),
                                erpOrder.getShopId());

                        jdbcTemplate.update("delete FROM erp_sales_order WHERE id=? ", salesOrder.getId());
                        jdbcTemplate.update("delete from erp_sales_order_item where orderId=?", salesOrder.getId());
                    } catch (Exception eee) {
                    }
                }
                // switch (ErpOrderSourceEnum.valueOf(erpOrder.getSource())) {
                // case YUNGOU:
                // case OFFLINE:
                // case DaiFa:
                // jdbcTemplate.update("UPDATE " + Tables.Order + " SET
                // auditStatus=0,send_status=? WHERE order_num=?",
                // EnumOrderSendStatus.WaitOut.getIndex(), erpOrder.getOrder_num());
                // break;
                // case ALIBABA:
                // jdbcTemplate.update("UPDATE " + Tables.DcAliOrder + " SET
                // auditStatus=0,send_status=? WHERE id=?",
                // EnumOrderSendStatus.WaitOut.getIndex(), erpOrder.getOrder_num());
                // break;
                // case TMALL:
                // case TAOBAO:
                // jdbcTemplate.update("UPDATE " + Tables.DcTmallOrder + " SET
                // auditStatus=0,send_status=? WHERE id=?",
                // EnumOrderSendStatus.WaitOut.getIndex(), erpOrder.getOrder_num());
                // break;
                // }

                successOrderTotal++;
            } catch (Exception e) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                errorOrderTotal++;
                continue;
            }
        }

        // TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return new ResultVo<>(EnumResultVo.SUCCESS, "操作成功，成功：" + successOrderTotal + "   失败：" + errorOrderTotal);
    }

    /**
     * 根据订单Id list获取商品列表并且去重
     *
     * @param
     * @return
     */
    public List<FaHuoDaiJianHuoGoodsVo> getDaiJianHuoOrderItemGoodsListAndDistinctSku(List<Long> orderIdList) {
        if (orderIdList == null) {
            StringBuilder sql = new StringBuilder();
            sql.append("SELECT ");
            sql.append(
                    " oi.skuId,egs.goodsId,egs.specNumber,egs.color_value,egs.color_image,egs.size_value,egs.style_value, ");
            sql.append(" eg.`name` AS goodsName,eg.`number` AS goodsNumber, ");
            sql.append(" SUM(oi.quantity) AS saleQty, ");
            // sql.append(" IFNULL((SELECT SUM(lockedQty) FROM erp_goods_stock_info egsi
            // WHERE egsi.specId=oi.skuId AND egsi.isDelete=0),0) AS lockedQty, ");
            sql.append(
                    " IFNULL((SELECT SUM(currentQty) FROM erp_goods_stock_info egsi WHERE egsi.specId=oi.skuId AND egsi.isDelete=0),0) AS currentQty ");
            sql.append(" ,COUNT(oi.id) AS orderItemCount,group_concat(oi.id) AS orderItems");
            sql.append(",COUNT(o.id) AS orderCount,group_concat(o.id) AS `orders` ");
            // sql.append(",egsi.locationId,esl.`number` AS locationNumber ");
            sql.append(" FROM erp_order_item oi  ");
            sql.append(" left join erp_goods_spec egs ON egs.id = oi.skuId ");
            sql.append(" LEFT JOIN erp_goods eg ON eg.id = egs.goodsId ");
            sql.append(" LEFT JOIN erp_order o ON o.id = oi.orderId ");
            // sql.append(" LEFT JOIN erp_goods_stock_info egsi ON egsi.specId = oi.skuId
            // ");
            // sql.append(" LEFT JOIN erp_stock_location esl ON esl.id = egsi.locationId ");
            sql.append(" WHERE oi.orderId IN (SELECT id FROM erp_order o WHERE o.`status` = 0) ");
            sql.append(" GROUP BY oi.skuId ");
            sql.append(" ORDER BY eg.`number` DESC  ");
            // sql.append(" ORDER BY saleQty DESC ");

            return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(FaHuoDaiJianHuoGoodsVo.class));
        }

        /************ 查询要加入拣货的订单 ***************/
        // String sql = "SELECT * FROM " + Tables.ErpOrder + " WHERE id in (:ids)";
        Map<String, Object> args = new HashMap<>();
        args.put("ids", orderIdList);
        NamedParameterJdbcTemplate givenParamJdbcTemp = new NamedParameterJdbcTemplate(jdbcTemplate);
        // 加入拣货单的订单list
        // List<ErpOrderEntity> orderList = givenParamJdbcTemp.query(sql, args, new
        // BeanPropertyRowMapper<>(ErpOrderEntity.class));

        // 加入拣货单的订单商品list（去重）
        // String itemSQL = "SELECT
        // productMallName,productId,productNumber,skuId,skuNumber,productImgUrl,SUM(quantity)
        // AS quantity FROM erp_order_item WHERE orderId IN (:ids) GROUP BY skuId";
        StringBuilder sb = new StringBuilder();
        // sb.append("SELECT
        // productMallName,productId,productNumber,skuId,skuNumber,productImgUrl,SUM(oi.quantity)
        // AS quantity,gs.color_value,gs.size_value");
        sb.append("SELECT ");
        sb.append(" egs.goodsId,egs.specNumber,egs.color_value,egs.color_image,egs.size_value,egs.style_value, ");
        sb.append(" eg.`name` AS goodsName,eg.`number` AS goodsNumber,");
        sb.append(" oi.skuId,SUM(oi.quantity) AS saleQty");
        sb.append(",(SELECT currentQty FROM erp_goods_spec WHERE id=skuId) AS currentQty");
        sb.append(",(SELECT SUM(lockedQty) FROM erp_goods_stock_info WHERE specId=skuId AND isDelete=0) AS lockedQty");
        sb.append(" ,COUNT(oi.id) AS orderItemCount,COUNT(o.id) AS orderCount ");
        sb.append(",egsi.locationId,esl.`number` AS locationNumber ");
        // sb.append(",IFNULL((SELECT SUM(it1.quantity) FROM erp_order_item AS it1 WHERE
        // it1.skuId=oi.skuId AND it1.`status` = 1 AND it1.orderId NOT IN (:ids)),0) AS
        // pickingQty");//在拣货中的订单items总数

        // sb.append(",(SELECT SUM(it1.quantity) FROM erp_order_item AS it1 WHERE
        // it1.skuId=skuId AND (it1.`status` = 0 OR it1.`status` = 1)) AS pickingQty");
        sb.append(" FROM erp_order_item  oi ");
        sb.append(" LEFT JOIN erp_order o ON o.id = oi.orderId ");
        sb.append(" LEFT JOIN erp_goods_spec egs on egs.id = oi.skuId ");
        sb.append(" LEFT JOIN erp_goods eg ON eg.id = egs.goodsId ");
        sb.append(" LEFT JOIN erp_goods_stock_info egsi ON egsi.specId = oi.skuId ");
        sb.append(" LEFT JOIN erp_stock_location esl ON esl.id = egsi.locationId ");
        sb.append(" WHERE oi.orderId IN (:ids) GROUP BY oi.skuId");
        sb.append(" ORDER BY esl.`number` ASC  ");

        return givenParamJdbcTemp.query(sb.toString(), args, new BeanPropertyRowMapper<>(FaHuoDaiJianHuoGoodsVo.class));
    }

    private StringBuilder queryOrderItemSQL() {
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT SQL_CALC_FOUND_ROWS oi.*,");
        sb.append("egs.color_image as goodsImg,");
        sb.append(
                "egs.color_value,egs.size_value,egs.style_value,eg.name as goodsName,eg.number as productNumber,sh.name as locationName,oi.quantity ");
        sb.append(
                ",o.order_num,IF(o.orderTime=0,o.createTime,o.orderTime) as orderTime,o.status as orderStatus,o.sale_type,o.contactPerson,o.deliveryTime");
        sb.append(",shop.name as shopName,unit.name as unitName ");
        sb.append(",(SELECT GROUP_CONCAT(goods_stock_info_item_id) FROM erp_stock_out_form_item_detail WHERE stock_out_form_item_id = oi.stockOutFormItemId) AS stockInfoItemId");
        // sb.append(",gsii.id AS stockInfoItemId ");
        sb.append(" FROM ");
        sb.append(Tables.ErpOrderItem).append(" as oi ");
        sb.append(" LEFT JOIN ").append(Tables.ErpOrder).append(" as o on o.id=oi.orderId ");
        sb.append(" LEFT JOIN ").append(Tables.ErpGoodsSpec).append(" as egs on egs.id=oi.skuId ");
        sb.append(" LEFT JOIN ").append(Tables.ErpGoods).append(" as eg on eg.id=oi.productId ");
        sb.append(" LEFT JOIN ").append(Tables.ErpUnit).append(" as unit on unit.id=eg.unitId ");
        sb.append(" LEFT JOIN ").append(Tables.ErpStockLocation).append(" as sh on sh.id=oi.outLocationId ");
        // sb.append(" LEFT JOIN ").append(Tables.ErpGoodsStockInfoItem)
        //         .append(" as gsii on gsii.id = oi.stockInfoItemId ");
        sb.append(" LEFT JOIN ").append(Tables.DcShop).append(" as shop on shop.id=o.shopId ");
        sb.append(" WHERE 1=1 ");
        return sb;
    }

    /**
     * 获取已发货的订单item
     * 
     * @param pageIndex
     * @param pageSize
     * @param orderNum
     * @param skuNumber
     * @param startTime
     * @param endTime
     * @return
     */
    @Transactional
    public PagingResponse<ErpOrderItemListVo> getOrderItemList(Integer pageIndex, Integer pageSize, String orderNum,
            String skuNumber, Integer startTime, Integer endTime, Integer orderStatus) {
        StringBuilder sb = queryOrderItemSQL();

        List<Object> params = new ArrayList<>();

        if (orderStatus != null) {
            sb.append(" AND o.status=? ");
            params.add(orderStatus);
        }
        // sb.append(" AND (o.status=? OR o.status =?) ");
        // params.add(EnumErpOrderSendStatus.HasSend.getIndex());//已出库状态的订单
        // params.add(EnumErpOrderSendStatus.HasOut.getIndex());//已出库状态的订单

        if (StringUtils.isEmpty(orderNum) == false) {
            sb.append(" AND o.order_num = ? ");
            params.add(orderNum);
        }
        if (StringUtils.isEmpty(skuNumber) == false) {
            sb.append(" AND oi.skuNumber = ? ");
            params.add(skuNumber);
        }

        if (startTime != null && startTime > 0) {
            sb.append("AND o.orderTime>=? ");
            params.add(startTime);
        }
        if (endTime != null && endTime > 0) {
            sb.append("AND o.orderTime<? ");
            params.add(endTime);
        }

        sb.append(" ORDER BY o.id DESC LIMIT ?,?");

        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);

        List<ErpOrderItemListVo> lists = jdbcTemplate.query(sb.toString(),
                new BeanPropertyRowMapper<>(ErpOrderItemListVo.class), params.toArray(new Object[params.size()]));

        return new PagingResponse<>(pageIndex, pageSize, getTotalSize(), lists);

    }

    public List<ErpOrderItemListVo> getOrderItemListForExcel(String orderNum, String skuNumber, Integer startTime,
            Integer endTime) {
        StringBuilder sb = queryOrderItemSQL();

        List<Object> params = new ArrayList<>();

        // sb.append(" AND o.status=? ");
        // params.add(EnumErpOrderSendStatus.HasSend.getIndex());//已出库状态的订单

        if (StringUtils.isEmpty(orderNum) == false) {
            sb.append(" AND o.order_num = ? ");
            params.add(orderNum);
        }
        if (StringUtils.isEmpty(skuNumber) == false) {
            sb.append(" AND oi.skuNumber = ? ");
            params.add(skuNumber);
        }

        if (startTime != null && startTime > 0) {
            sb.append("AND o.orderTime>=? ");
            params.add(startTime);
        }
        if (endTime != null && endTime > 0) {
            sb.append("AND o.orderTime<? ");
            params.add(endTime);
        }

        sb.append(" ORDER BY o.id DESC");

        return jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(ErpOrderItemListVo.class),
                params.toArray(new Object[params.size()]));
    }

    public void updErpOrderReturnCode(Long id, String company, String expressCode) {
        jdbcTemplate.update("update erp_order_return set logisticsCompany=?,logisticsCode=? where id=?", company,
                expressCode, id);
    }

    public List<OrderScanCodeVo> getOrderAndItemsByLogisticsCodeOrorderNum(String num) {

        StringBuffer sb = new StringBuffer();
        sb.append(
                "SELECT  A.id,A.order_num as sn,A.stockOutTime as t,CONCAT(A.province,A.city,A.area) as ad,A.logisticsCode as k,A.status as st");
        // sb.append(",(SELECT SUM(quantity) FROM " + Tables.ErpOrderItem + " WHERE
        // orderId=A.id ) as totalQuantity");
        sb.append(",shop.name as s ");
        sb.append(" FROM " + Tables.ErpOrder + " as A ");
        sb.append(" LEFT JOIN  " + Tables.DcShop + " as shop ON shop.id = A.shopId ");

        List<Object> params = new ArrayList<>();
        // sb.append(" WHERE A.status = 1 ");
        sb.append(" WHERE 1 = 1 ");

        if (!StringUtils.isEmpty(num)) {
            sb.append("AND (A.order_num = ? OR A.logisticsCode = ? )");
            params.add(num);
            params.add(num);
        }

        sb.append(" ORDER BY A.id DESC ");

        List<OrderScanCodeVo> lists = jdbcTemplate.query(sb.toString(),
                new BeanPropertyRowMapper<>(OrderScanCodeVo.class), params.toArray(new Object[params.size()]));

        if (lists != null && lists.size() > 0) {
            String itemSQL = "SELECT oi.skuNumber as sN,oi.quantity as qty FROM " + Tables.ErpOrderItem
                    + " as oi LEFT JOIN " + Tables.ErpGoodsSpec + " as gs on gs.id = oi.skuId WHERE oi.orderId=?";
            for (OrderScanCodeVo vo : lists) {
                vo.setItems(jdbcTemplate.query(itemSQL, new BeanPropertyRowMapper<>(OrderItemScanCodeVo.class),
                        vo.getId()));
            }
        }
        return lists;
    }

    public List<OrderScanCodeVo> getOrderAndItemsByLogisticsCodeOrordeId(List orderIdArr) {

        StringBuffer sb = new StringBuffer();
        sb.append(
                "SELECT  A.id,A.order_num as sn,A.stockOutTime as t,CONCAT(A.province,A.city,A.area) as ad,A.logisticsCode as k,A.status as st");
        sb.append(",shop.name as s ");
        sb.append(" FROM " + Tables.ErpOrder + " as A ");
        sb.append(" LEFT JOIN  " + Tables.DcShop + " as shop ON shop.id = A.shopId ");

        sb.append(" WHERE A.id IN (:ids) ");

        sb.append(" ORDER BY A.id DESC ");
        Map<String, Object> args = new HashMap<>();
        args.put("ids", orderIdArr);
        NamedParameterJdbcTemplate givenParamJdbcTemp = new NamedParameterJdbcTemplate(jdbcTemplate);

        List<OrderScanCodeVo> lists = givenParamJdbcTemp.query(sb.toString(), args,
                new BeanPropertyRowMapper<>(OrderScanCodeVo.class));

        if (lists != null && lists.size() > 0) {
            String itemSQL = "SELECT oi.skuNumber as sN,oi.quantity as qty FROM " + Tables.ErpOrderItem
                    + " as oi LEFT JOIN " + Tables.ErpGoodsSpec + " as gs on gs.id = oi.skuId WHERE oi.orderId=?";
            for (OrderScanCodeVo vo : lists) {
                vo.setItems(jdbcTemplate.query(itemSQL, new BeanPropertyRowMapper<>(OrderItemScanCodeVo.class),
                        vo.getId()));
            }
        }

        return lists;
    }

    public OrderWaitSendListVo getOrderAndItemsByOrderId(Long orderId) {

        StringBuffer sb = new StringBuffer();
        sb.append("SELECT  A.*,(SELECT SUM(quantity) FROM " + Tables.ErpOrderItem
                + " WHERE orderId=A.id ) as totalQuantity,shop.name as shopName ");
        sb.append(" FROM " + Tables.ErpOrder + " as A ");
        sb.append(" LEFT JOIN  " + Tables.DcShop + " as shop ON shop.id = A.shopId ");

        List<Object> params = new ArrayList<>();
        sb.append(" WHERE A.id=? ");
        params.add(orderId);
        sb.append(" LIMIT 1 ");

        OrderWaitSendListVo order = jdbcTemplate.queryForObject(sb.toString(),
                new BeanPropertyRowMapper<>(OrderWaitSendListVo.class), params.toArray(new Object[params.size()]));

        if (order != null) {
            String itemSQL = "SELECT oi.*,gs.color_value,gs.size_value,gs.color_image FROM " + Tables.ErpOrderItem
                    + " as oi LEFT JOIN " + Tables.ErpGoodsSpec + " as gs on gs.id = oi.skuId WHERE oi.orderId=?";
            order.setItems(
                    jdbcTemplate.query(itemSQL, new BeanPropertyRowMapper<>(ErpOrderItemEntity.class), order.getId()));

        }
        return order;
    }

    public ResultVo<Integer> addErpOrderReturnItem(Long id, String specNumber, Integer num) {
        ErpGoodsSpecEntity erpGoodsSpec = null;
        try {
            erpGoodsSpec = jdbcTemplate.queryForObject("select spec.*,(select NUMBER from erp_goods where id=spec.goodsId) goodsNumber from erp_goods_spec spec where spec.specNumber=? LIMIT 1", new BeanPropertyRowMapper<>(ErpGoodsSpecEntity.class), specNumber.trim());
        } catch (Exception E) {
            return new ResultVo<>(EnumResultVo.DataError, "SKU【" + specNumber + "】不存在");
        }

        String sql="insert erp_order_return_item set orderId=?,orderItemId=?,goodsId=?,skuId=?,skuNumber=?,quantity=?,inQuantity=0,badQuantity=0,receiveType=1,createTime=unix_timestamp(now()),status=?,refundAmount=? ";
        jdbcTemplate.update(sql,id,0,erpGoodsSpec.getGoodsId(),erpGoodsSpec.getId(),erpGoodsSpec.getSpecNumber(),num,0,0);
        return new ResultVo<>(EnumResultVo.SUCCESS,"成功");
    }

    public List<DouYinOrderCountVo> getDouYinOrderCount(String strDate,String endDate){
        List<Object> params = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        sb.append("select COUNT(0) orderCount,SUM(order_total_amount) orderAmount, FROM_UNIXTIME(create_time,'%Y-%m-%d') orderDate from dc_douyin_orders WHERE  (order_status=1 OR order_status=2  OR order_status=3 OR order_status=5) ");
        if (!StringUtils.isEmpty(strDate)) {
            sb.append(" AND FROM_UNIXTIME(create_time,'%Y-%m-%d')>=? ");
            params.add(strDate);
        }
        if (!StringUtils.isEmpty(endDate)) {
            sb.append(" AND FROM_UNIXTIME(create_time,'%Y-%m-%d')<? ");
            params.add(endDate);
        }
        sb.append(" GROUP BY orderDate " );
        return jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(DouYinOrderCountVo.class),
                params.toArray(new Object[params.size()]));
    }

    public List<ErpOrderItemEntity> douyinOrderSettleExport (String startDate, String endDate){
        StringBuilder sb =new StringBuilder("SELECT e.order_num stockOutNo,i.productNumber ,i.skuNumber ,i.quantity ,i.itemAmount ,i.purPrice ,FROM_UNIXTIME(e.orderTime,'%Y-%m-%d %H:%i:%s') locationName from erp_order_item i LEFT JOIN erp_order e ON i.orderId=e.id WHERE  \n" +
                " e.settleSign=1 ");
        List<Object> params = new ArrayList<>();
        if(!StringUtils.isEmpty(startDate)) {
            //按一级大类查询
            sb.append(" AND FROM_UNIXTIME(e.orderTime,'%Y-%m-%d') >= ? ");
            params.add(startDate);
        }

        if(!StringUtils.isEmpty(endDate)) {
            //按一级大类查询
            sb.append(" AND FROM_UNIXTIME(e.orderTime,'%Y-%m-%d') <= ?");
            params.add(endDate);
        }
        var list = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(ErpOrderItemEntity.class), params.toArray(new Object[params.size()]));
        return list;
    }
    public void douyinOrderSettle(List<Long> ids,Integer isSettle){
        for(var id : ids){
            jdbcTemplate.update("update erp_order set settleSign=? where order_num=?",isSettle,String.valueOf(id));
        }
    }

}
